package com.alex.seo.service.sitebridge.wordpress;

import java.net.MalformedURLException;

import net.bican.wordpress.Page;
import net.bican.wordpress.Wordpress;

import org.apache.commons.lang.StringUtils;

import redstone.xmlrpc.XmlRpcFault;

import com.alex.seo.contentsource.dto.ContentDTO;
import com.alex.seo.service.sitebridge.SiteBridge;
import com.alex.seo.service.sitebridge.SiteBridgeException;
import com.alex.seo.service.sitebridge.dto.PageDTO;

public class WordpressBridge implements SiteBridge {

	private Wordpress wordpress;
	
	public WordpressBridge(String url, String login, String password) throws MalformedURLException {
		this.wordpress = new Wordpress(login, password, url);
	}
	
	@Override
	public PageDTO createPost(ContentDTO contentDTO) throws SiteBridgeException {
		try {
			Page page = new Page();
			page.setTitle(contentDTO.getTitle());
			page.setDescription(contentDTO.getText());
			
			if (contentDTO.getKeywords() != null && !contentDTO.getKeywords().isEmpty()) {
				page.setMt_keywords(StringUtils.join(contentDTO.getKeywords(), ","));
			}
			
			Integer id = Integer.valueOf(wordpress.newPost(page, true));
			page = wordpress.getPost(Integer.valueOf(id));
			
			return new PageDTO(id, page.getLink());
		} catch (XmlRpcFault e) {
			throw new SiteBridgeException(e);
		}
	}

}
